package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName ApUserServiceImpl
 * @Description TODO
 * @Author kiku
 * @Date 2024/8/9 13:00
 * @Version 1.0
 */
@Service
@Transactional
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {


    @Override
    public ResponseResult login(LoginDto loginDto) {
        //正常登录
        if (StringUtils.isNotEmpty(loginDto.getPhone()) &&
                StringUtils.isNotEmpty(loginDto.getPassword())) {
            //1.1根据手机号查用户
            ApUser user = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()));
            if (user == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户信息不存在");

            }
            //1.2比对密码
            String salt = user.getSalt();
            String password = loginDto.getPassword();
            String md5Hex = DigestUtils.md5Hex((password + salt).getBytes());
            if (!md5Hex.equals(user.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码错误");

            }
            //1.3返回数据
            String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            user.setPassword(null);
            user.setSalt(null);
            map.put("user",user);
            return ResponseResult.okResult(map);
        }else {
            //游客登陆
            Map<String, Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }
}
